package com.weixx.yctp.user.controller;

import cc.eamon.open.permission.Limit;
import cc.eamon.open.permission.annotation.Permission;
import cc.eamon.open.permission.annotation.PermissionLimit;
import cc.eamon.open.status.Status;
import cc.eamon.open.status.StatusCode;
import cc.eamon.open.status.StatusException;
import com.weixx.yctp.user.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Api(
        value="用户-角色授权",
        tags = "用户-角色授权"
)
@RestController
@RequestMapping("/userole")
@Permission("adm_mark")
public class UserRoleController {
    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation(value="授予用户权限", tags = "授予用户权限")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "", method = RequestMethod.POST)
    @PermissionLimit(limits = Limit.OPERATION_RETRIEVE)
    public Status SetUserRole(@RequestParam Integer userId, @RequestParam Integer roleId, HttpServletRequest req) throws Exception{
        //取缓存的值
        String loginName = null;
        Cookie[] cookies = req.getCookies();
        if (cookies == null) throw new StatusException("未登录");
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("userName")) {
                loginName = cookie.getValue();
            }
        }
        return new Status(
                true,
                StatusCode.getCode("SUCCESS"),
                userRoleService.setUserRole(userId,roleId,loginName),
                "授权成功"

        );
    }

}
